<?php

namespace common\service;

use common\libs\Curl;

class SteamService
{
	public static $instance = null;
	public static $URL = 'http://api.steampowered.com/ISteamEconomy/GetAssetClassInfo/v0001?';
	public static $TRADEHISTORY = 'https://api.steampowered.com/IEconService/GetTradeHistory/v1?';
	public static $TRADEOFFER = 'https://api.steampowered.com/IEconService/GetTradeOffer/v1?';
	public static $TRADEOFFERS = 'https://api.steampowered.com/IEconService/GetTradeOffers/v1?';
	public static $CancelTRADEOFFER = 'https://api.steampowered.com/IEconService/CancelTradeOffer/v1?';
	public static $TRADESTATUS= 'https://api.steampowered.com/IEconService/GetTradeStatus/v1?';

	public static $OWNGAMES = 'https://api.steampowered.com/IPlayerService/GetOwnedGames/v1?';
	public static $STEAMLEVEL = 'https://api.steampowered.com/IPlayerService/GetSteamLevel/v1?';
	public static $FRIENDLIST = 'https://api.steampowered.com/ISteamUser/GetFriendList/v1?';
	
	private function __construct(){
		
	}
	public static function getInstance(){
		if(self::$instance == null){
			self::$instance = new self();
		}
		return self::$instance;
	}
	
	
	public function getOffers($apiKey){
		//https://api.steampowered.com/IEconService/GetTradeOffers/v1/?key=9DFE1BA9F158478C4E789F9E2CCCB172&get_sent_offers=1&get_received_offers=1
		try{
			$params = array(
					'key'=>$apiKey,
					'get_sent_offers'=>1,
					'active_only'=>1,
					'format'=>'json',
			);
			$url = self::$TRADEOFFERS.http_build_query($params);
			$result = Curl::http_get($url);
			$result = json_decode($result ,true);
			if(!empty($result['response'])){
				return $result['response'];
			}
			return false;
		}catch (\Exception $e){
			echo $e->getMessage();
			return false;
		}
	}
	public function cancelTradeById($key,$tradeofferId){
		try{
			$params = array(
					'key'=>$key,
					'tradeofferid'=>$tradeofferId,
					'format'=>'json',
			);
			$url = self::$CancelTRADEOFFER.http_build_query($params);
			$result = Curl::http_post(self::$CancelTRADEOFFER, $params);
			$result = json_decode($result ,true);
			if(isset($result['response'])){
				return true;
			}
			return false;
		}catch (\Exception $e){
			echo $e->getMessage();
			return false;
		}
	}
	
	public function getTradeoffer($key,$tradeofferId,$time=0,$isProy = false){
		try{
			$params = array(
					'key'=>$key,
					'tradeofferid'=>$tradeofferId,
					'format'=>'json',
			);
			$url = self::$TRADEOFFER.http_build_query($params);
			if($isProy == true){
				$result = Curl::steamprice_proxy_curl($url);
			}else{
				$result = Curl::http_get($url);
			}
			if(empty($result)){
				return false;
			}
			$result = json_decode($result ,true );
			if(!empty($result['response']['offer'])){
				return $result['response']['offer'];
			}elseif($time<2){
				$time += 1;
				return $this->getTradeoffer($key, $tradeofferId,$time);
			}else{
				return false;
			}
		}catch (\Exception $e){
			echo $e->getMessage();
			return false;
		}
	}
	
	public function getTradeOfferHistoryList($key,$limit = 500){
		try{
			$params = array(
					'key'=>$key,
					'max_trades'=>$limit,
					'format'=>'json',
					'include_failed'=>1
			);
			$url = self::$TRADEHISTORY.http_build_query($params);
			$items = [];
			echo $url."\n";
			$result = Curl::http_get($url);
			if(empty($result)){
				return false;
			}
			$result = json_decode($result ,true );
			if(!empty($result['response']['trades'])){
				return $result['response']['trades'];
			}
			return false;
		}catch (\Exception $e){
			echo $e->getMessage();
			return false;
		}
	}
	
	public function getTradeStatus($apiKey,$tradeId){
		try{
			$params = array(
					'key'=>$apiKey,
					'format'=>'json',
					'tradeid'=>$tradeId,
			);
			$url = self::$TRADESTATUS.http_build_query($params);
			$items = [];
			echo $url;
			$result = Curl::http_get($url);
			if(empty($result)){
				return false;
			}
			$result = json_decode($result ,true );
			if(!empty($result['response']['trades'][0])){
				foreach ($result['response']['trades'][0]['assets_received'] as $item){
					$items[] =(Object)[
							'assetid' => $item['assetid'],
							'new_assetid'=>	$item['new_assetid'],
							'classid'=>	$item['classid'],
							'instanceid'=>	$item['instanceid'],
							'amount'=>$item['amount']
						];
				}
				return $items;
			}
			return false;
		}catch (\Exception $e){
			echo $e->getMessage();die;
			return false;
		}
	}
	
	public function getTradeofferHistory($key,$tradeofferId,$limit=500){
		try{
			$params = array(
					'key'=>$key,
					'max_trades'=>$limit,
					'format'=>'json',
					'include_failed'=>1
			);
			$url = self::$TRADEHISTORY.http_build_query($params);
			$items = [];
			echo $url;
			$result = Curl::http_get($url);
			if(empty($result)){
				return false;
			}
			$result = json_decode($result ,true );
			if(!empty($result['response']['trades'])){
				foreach ($result['response']['trades'] as $trade){
					if($trade['tradeid'] == $tradeofferId){
						foreach ($trade['assets_received'] as $item){
							$items[] = (Object)([
									'id'=>	$item['new_assetid'],
									'classid'=>	$item['classid'],
									'instanceid'=>	$item['instanceid'],
									'amount'=>$item['amount']
							]); 
						}
					}
				}
			}
			return $items;
		}catch (\Exception $e){
			echo $e->getMessage();
			return false;
		}
	}
	public function getAssectInfo($apiKey,$appid,$classIds){
		try{
			$count = count($classIds);
			$time = ceil($count / 100);
			$res = [];
			for ( $i = 0;$i< $time;$i++){
				$key = $i * 100;
				$nextCount = ($i+1) * 100;
				
				$nextCount = ($nextCount) > $count ? $count : $nextCount;
				$params = array(
						'key'=>$apiKey,
						'format'=>'json',
						'appid'=>$appid,
						'language'=>'zh-cn',
						'class_count'=>100,
				);
				$index = 0;
				for ($j=$key;$j < $nextCount ;$j++){
					$params['classid'.$index] = $classIds[$j];
					$index++;
				}
				$url = self::$URL.http_build_query($params);
				echo $url;
				$result = Curl::http_get($url);
				$result = json_decode($result ,true );
				$result = $result['result'];
				foreach ($result as $classId =>$item){
					$res[$classId] = $item;
				}
				echo "$count 物品需要抓取 \n";
				sleep(1);
			}
			return $res;
		}catch (\Exception $e){
			echo $e->getMessage();
			return false;
		}
	}

	public function getOwnedGames($apiKey, $steamId)
	{
		try{
			$params = array(
				'key' => $apiKey,
				'steamid' => $steamId,
				'include_appinfo' => false,
				'include_played_free_games' => false,
				'format' => 'json',
			);
			$url = self::$OWNGAMES.http_build_query($params);
			$result = Curl::http_get($url);
			$result = json_decode($result ,true);
			if(!empty($result['response'])){
				return $result['response'];
			}
			return false;
		}catch (\Exception $e){
			echo $e->getMessage();
			return false;
		}
	}

	public function getSteamLevel($apiKey, $steamId)
	{
		try{
			$params = array(
				'key' => $apiKey,
				'steamid' => $steamId,
				'format' => 'json',
			);
			$url = self::$STEAMLEVEL.http_build_query($params);
			$result = Curl::http_get($url);
			$result = json_decode($result ,true);
			if(!empty($result['response'])){
				return $result['response'];
			}
			return false;
		}catch (\Exception $e){
			echo $e->getMessage();
			return false;
		}
	}

	public function getFriendList($apiKey, $steamId)
	{
		try{
			$params = array(
				'key' => $apiKey,
				'steamid' => $steamId,
				'format' => 'json',
			);
			$url = self::$FRIENDLIST.http_build_query($params);
			$result = Curl::http_get($url);
			$result = json_decode($result ,true);
			if(!empty($result['friendslist'])){
				return $result['friendslist'];
			}
			return false;
		}catch (\Exception $e){
			echo $e->getMessage();
			return false;
		}
	}
}